<?php

namespace addons\epay\controller;

use addons\epay\library\Service;
use fast\Random;
use think\addons\Controller;
use app\api\controller\Send;
use app\api\controller\Goeasy;
use Exception;
use think\Db;

/**
 * 微信支付宝插件首页
 *
 * 此控制器仅用于开发展示说明和体验，建议自行添加一个新的控制器进行处理返回和回调事件，同时删除此控制器文件
 *
 * Class Index
 * @package addons\epay\controller
 */
class Index extends Controller
{

    protected $layout = 'default';

    protected $config = [];

    public function _initialize()
    {
        parent::_initialize();
        if (!config("app_debug")) {
            $this->error("仅在开发环境下查看");
        }
    }

    public function index()
    {
        $this->view->assign("title", "微信支付宝整合插件");
        return $this->view->fetch();
    }

    /**
     * 体验，仅供开发测试
     */
    public function experience()
    {
        $amount = $this->request->request('amount');
        $type = $this->request->request('type');
        $method = $this->request->request('method');

        if (!$amount || $amount < 0) {
            $this->error("支付金额必须大于0");
        }

        if (!$type || !in_array($type, ['alipay', 'wechat'])) {
            $this->error("支付类型不能为空");
        }

        //订单号
        $out_trade_no = date("YmdHis") . mt_rand(100000, 999999);

        //订单标题
        $title = '测试订单';

        //回调链接
        $notifyurl = $this->request->root(true) . '/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $out_trade_no;

        $response = Service::submitOrder($amount, $out_trade_no, $type, $title, $notifyurl, $returnurl, $method);

        return $response;
    }

    /**
     * 支付成功，仅供开发测试
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        //添加分组，只有投诉咨询和一级客服可以分配
        $auth_group = DB::name("auth_group")->where(['name'=>['in',['投诉咨询','一级客服']]])->column('id');
        $auth_group_access = DB::name("auth_group_access")->where(['group_id'=>['in',$auth_group]])->column("uid");
        $admin_id = Db::name('admin')->where(['status'=>'normal','id'=>['in',$auth_group_access]])->orderRaw('Rand()')->value('id');
        file_put_contents('aa.log',$paytype);
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        file_put_contents('ab.log',$data);
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $type = $paytype == 'alipay' ? '支付宝' : '微信';
            $out_trade_no = $data['out_trade_no'];

            //你可以在此编写订单逻辑
            $order = db::name('order')->where('order_sn',$out_trade_no)->find();
            $goods = Db::name('goods')->where('id',$order['goods_id'])->find();
            $user = Db::name('personal')->where('id',$order['buyid'])->value('switch');
            if ($user == 2) {
                $ret1 = [
                    'uid'   =>  $order['buyid'],
                    'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                    'money' =>  '-'.$order['amount'],
                    'type'  =>  1,
                    'content'   =>  '消费',
                    'createtime'    =>  time(),
                    'arrivaltime'   =>  time(),
                    'status'    =>  1
                ];
                $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>30,'paytime'=>time(),'payway'=>$type]);
                $re['s2'] = Db::name('account_log')->insert($ret1);
            } else {
                if ($goods['goods_class_type'] == 1) {
                    $ret1 = [
                        'uid'   =>  $order['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$order['amount'],
                        'type'  =>  1,
                        'content'   =>  '消费',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
                    $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>11,'paytime'=>time(),'payway'=>$type]);
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                    $easy = new Goeasy();
                    $msg = '您有待验证的订单了!';
                    $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
                } else {
                    $ret1 = [
                        'uid'   =>  $order['buyid'],
                        'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                        'money' =>  '-'.$order['amount'],
                        'type'  =>  1,
                        'content'   =>  '消费',
                        'createtime'    =>  time(),
                        'arrivaltime'   =>  time(),
                        'status'    =>  1
                    ];
//                $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
                    if ($goods['method'] == 3) {
                        $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>5,'paytime'=>time(),'payway'=>$type]);
                    } else {
                        $re['s1'] = Db::name('order')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
                    }
                    $re['s2'] = Db::name('account_log')->insert($ret1);
                    $send = new Send();
                    $re['s3'] = $send->send($goods['mobile'],2);
                    $easy = new Goeasy();
                    $msg = '您有待发货的订单了!';
                    $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
                }
            }
        } catch (Exception $e) {
        }
        if ($paytype == 'alipay') {
            return 'success';
        } else {
            return 'SUCCESS';
        }


    }

    /**
     * 支付返回，仅供开发测试
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里通过out_trade_no去验证订单状态
        //但是不可以在此编写订单逻辑！！！

//        $this->success("请返回网站查看支付结果", addon_url("/paySuccess"));
        $this->success("请返回网站查看支付结果", "https://ceshi.780g.com/orderhandling/Ording?tag=seller-finished");
    }


	public function returnr()
	{
		$paytype = $this->request->param('paytype');
		$out_trade_no = $this->request->param('out_trade_no');
		$pay = Service::checkReturn($paytype);
		if (!$pay) {
			$this->error('签名错误', '');
		}

		//你可以在这里通过out_trade_no去验证订单状态
		//但是不可以在此编写订单逻辑！！！

//        $this->success("请返回网站查看支付结果", addon_url("/paySuccess"));
		$this->success("请返回网站查看支付结果", "https://ceshi.780g.com/Mycenter/ppinf");
	}

}
